package cn.com.gzheroli.bfw.web.system.controler.core;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;

import cn.com.gzheroli.bfw.pojo.base.TSDepart;
import cn.com.gzheroli.bfw.pojo.base.TSTerritory;
import cn.com.gzheroli.core.common.controller.BaseController;
import cn.com.gzheroli.core.common.model.json.AjaxJson;
import cn.com.gzheroli.core.common.model.json.ComboTree;
import cn.com.gzheroli.core.common.model.json.TreeGrid;
import cn.com.gzheroli.core.common.service.CommonService;
import cn.com.gzheroli.core.common.service.SystemService;
import cn.com.gzheroli.core.constant.Globals;
import cn.com.gzheroli.core.util.IdWorker;
import cn.com.gzheroli.core.util.LogUtil;
import cn.com.gzheroli.core.util.StringUtil;
import cn.com.gzheroli.rabbitmq.service.log.LogService;
import cn.com.gzheroli.service.bfw.TerritoryService;
import cn.com.gzheroli.tag.vo.easyui.ComboTreeModel;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;


/**
 * 地域处理类
 */
@Controller
@RequestMapping("/territoryController")
public class TerritoryController extends BaseController {
	
	private String message = null;
	
	@Autowired
	private SystemService systemService;
	@Autowired
	private TerritoryService territoryService;
	
	@Autowired
	private LogService logService;
	@Autowired
	private CommonService commonService;
	/**
	 * 地域列表页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "territory")
	public ModelAndView function() {
		return new ModelAndView("system/territory/territoryList");
	}

	
	/**
	 * 地域列表
	 */
	@RequestMapping(params = "territoryGrid")
	@ResponseBody
	public List<Map> territoryGrid(HttpServletRequest request, TreeGrid treegrid) {
		/*CriteriaQuery cq = new CriteriaQuery(TSTerritory.class);
			if (treegrid.getId() != null) {
				cq.eq("TSTerritory.id", treegrid.getId());
			}
			if (treegrid.getId() == null) {
				cq.eq("TSTerritory.id","1");//这个是全国最高级
			}
		
		cq.addOrder("territorySort", SortDirection.asc);
		cq.add();
		List<TSTerritory> territoryList = systemService.getListByCriteriaQuery(cq, false);
		List<TreeGrid> treeGrids = new ArrayList<TreeGrid>();
		TreeGridModel treeGridModel = new TreeGridModel();
		treeGridModel.setIcon("");
		treeGridModel.setTextField("territoryName");
		treeGridModel.setParentText("TSTerritory_territoryName");
		treeGridModel.setParentId("TSTerritory_id");
		treeGridModel.setSrc("territoryCode");
		treeGridModel.setIdField("id");
		treeGridModel.setChildList("TSTerritorys");
		treeGridModel.setOrder("territorySort");
		treeGrids = systemService.treegrid(territoryList, treeGridModel);*/
		List<Map> treeGrids = new ArrayList<Map>();
		Map dataMap=new HashMap();
		dataMap.put("pid", request.getParameter("id"));
		treeGrids =territoryService.getTerritoryList(dataMap);
		return treeGrids;
	}
	/**
	 *地域列表页面跳转
	 * 
	 * @return
	 */
	@RequestMapping(params = "addorupdate")
	public ModelAndView addorupdate(TSTerritory territory, HttpServletRequest req) {
		String id = req.getParameter("id");
		territory=territoryService.getTerritory(id);
		req.setAttribute("territory", territory);
		return new ModelAndView("system/territory/territory");
	}
	/**
	 * 地域父级下拉菜单
	 */
	@RequestMapping(params = "setPTerritory")
	@ResponseBody
	public List<Map> setPTerritory(HttpServletRequest request, ComboTree comboTree) {
		return territoryService.setPTerritory(comboTree.getId());
	}
	/**
	 * 级联更新部门级别编号，便于查询所有子部门
	 * @param request
	 * @return
	 */
	@RequestMapping(params = "casedUpdateDeptLevelNo")
	@ResponseBody
	public synchronized AjaxJson casedUpdateAreaLevelNo(HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		territoryService.updateAreaLevelNoCased("","");
		j.setSuccess(true);
		j.setMsg("更新成功");
		return j;
	}
	/**
	 * 地域保存
	 */
	@RequestMapping(params = "saveTerritory")
	@ResponseBody
	public AjaxJson saveTerritory(TSTerritory territory, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		
		String functionOrder = territory.getTerritorySort();
		String pid=territory.getParentId();
		if(StringUtils.isEmpty(functionOrder)){
			territory.setTerritorySort("0");
		}
		if (territory.getParentId().equals("")) {
			territory.setParentId("");
		}else{
			TSTerritory parent = commonService.getEntity(TSTerritory.class, territory.getParentId());
			territory.setTerritoryLevel(Short.valueOf(parent.getTerritoryLevel()+1+""));
		}
		if (StringUtil.isNotEmpty(territory.getId())) {
			TSTerritory oldArea=commonService.getEntity(TSTerritory.class, territory.getId());
			if(!oldArea.getParentId().equals(territory.getParentId())||territory.getLevelNo()==null||territory.getLevelNo().trim().equals("")){
				TSTerritory pArea=commonService.getEntity(TSTerritory.class, pid);
				String sql="select LEVEL_NO  from t_s_territory where PARENT_ID=#{pid}  and (LEVEL_NO is not null and LEVEL_NO!='') order by LEVEL_NO";
				Map para=new HashMap();
				para.put("pid", pid);
				Map map=commonService.findOneForJdbc(sql,para );
				String pLevelNo=pArea.getLevelNo()==null?"":pArea.getLevelNo();
				String levelNo=map==null||map.get("levelNo")==null?pLevelNo+"000":(String)map.get("levelNo");
				String newLevelNo=StringUtil.fillDepartLevel(pLevelNo,levelNo);
				territory.setLevelNo(newLevelNo);
			}
			message = "地域: " + territory.getTerritoryName() + "被更新成功";
			commonService.update(territory);
			logService.addLog(message, Globals.Log_Type_UPDATE, Globals.Log_Leavel_INFO,LogUtil.logReqMap(request));
		} else {
			TSTerritory pArea=commonService.getEntity(TSTerritory.class, pid);
			//String sql="select max(cast(ID as INTEGER)) ID from T_S_DEPART";
			String sql="select LEVEL_NO  from t_s_territory where PARENT_ID=#{pid}  and (LEVEL_NO is not null and LEVEL_NO!='') order by LEVEL_NO";
			Map para=new HashMap();
			para.put("pid", pid);
			Map map=commonService.findOneForJdbc(sql,para );
			String pLevelNo=pArea.getLevelNo()==null?"":pArea.getLevelNo();
			String levelNo=map==null||map.get("levelNo")==null?pLevelNo+"000":(String)map.get("levelNo");
			String newLevelNo=StringUtil.fillDepartLevel(pLevelNo,levelNo);
			territory.setLevelNo(newLevelNo);
			territory.setTerritorySort(territory.getTerritorySort());
			territory.setId(IdWorker.getFlowIdWorkerInstance().nextIdStr());
			message = "地域: " + territory.getTerritoryName() + "被添加成功";
			commonService.save(territory);
			logService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO,LogUtil.logReqMap(request));

		}
		
		return j;
	}

	/**
	 * 地域删除
	 * 
	 * @param ids
	 * @return
	 */
	@RequestMapping(params = "del")
	@ResponseBody
	public AjaxJson del(TSTerritory territory, HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		territory = commonService.getEntity(TSTerritory.class, territory.getId());
		message = "地域: " + territory.getTerritoryName() + "被删除成功";
		commonService.delete(TSTerritory.class, territory.getId());
		logService.addLog(message, Globals.Log_Type_DEL, Globals.Log_Leavel_INFO,LogUtil.logReqMap(request));
		return j;
	}

}
